const Service = require('egg').Service
const crypto = require('crypto')

class WechatService extends Service {
  async parseEncryptedData ({sessionKey, encryptedData, iv}) {
    // base64 decode
    const _sessionKey = new Buffer(sessionKey, 'base64')
    encryptedData = new Buffer(encryptedData, 'base64')
    iv = new Buffer(iv, 'base64')
    let decoded = ''
    try {
      // 解密
      const decipher = crypto.createDecipheriv('aes-128-cbc', _sessionKey, iv)
      // 设置自动 padding 为 true，删除填充补位
      decipher.setAutoPadding(true)
      decoded = decipher.update(encryptedData, 'binary', 'utf8')
      decoded += decipher.final('utf8')
      decoded = JSON.parse(decoded)
    } catch (e) {
      let err = 'decode error'
      console.debug(e, err)
      throw err
    }

    if (decoded.watermark.appid !== this.config.wechat.APPID) {
      throw 'decoded.appid not match'
    }

    return decoded
  }

  async getInfoByCode ({code}) {
    const axios = require('axios')
    let rz = await axios.get('https://api.weixin.qq.com/sns/jscode2session', {
      params: {
        appid: this.config.wechat.APPID,
        secret: this.config.wechat.SECRET,
        grant_type: 'authorization_code',
        js_code: code
      }
    })
    let data = rz.data
    let sessionKey = data.session_key
    if (!sessionKey) {
      let err = 'failed to get session_key'
      console.debug(rz, err)
      throw err
    }

    return data
  }
}

module.exports = WechatService